import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';
import { Logger } from '@/logger';
import { ResultData } from '@/common/dto/result';

interface Response<T> {
  code?: number;
  msg?: string;
  data: T;
}

@Injectable()
export class TransformInterceptor implements NestInterceptor<ResultData, Response<ResultData>> {
  // 拦截器的实现
  intercept(
    context: ExecutionContext,
    next: CallHandler<ResultData>
  ): Observable<Response<ResultData>> {
    // 获取请求和响应对象
    // next.handle()返回的是一个Observable<T>类型的数据
    return next.handle().pipe(
      // map是 rxjs 的一个内置操作符，用于对数据进行转换
      map((data) => {
        // 获取响应的数据
        const ctx = context.switchToHttp();
        // 获取响应对象
        const response = ctx.getResponse();
        // 获取请求对象
        const request = ctx.getRequest();

        const statusCode = response.statusCode;
        // 获取请求的路由
        const url = request.originalUrl;

        const res = {
          statusCode,
          errorCode: data.code ? data.code : null,
          msg: data.msg,
          success: true,
          data: data.data,
        };
        // 记录请求和响应的日志
        Logger.info(`
        -----------------------------------------------------------------------
        Request originalUrl: ${url}
        Method: ${request.method}
        StatusCode: ${statusCode}
        Response: ${JSON.stringify(data)}
        -----------------------------------------------------------------------
        `);
        return res;
      })
    );
  }
}
